from config import config
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_session import Session
# CSRF保护 1 在所用['POST', 'PUT', 'PATCH', 'DELETE']等请求后（利用请求钩子） 对app进行CSRF申请令牌，cookie传递token的值
# 2 在ajax请求中设置请求传递的参数
from flask_wtf import CSRFProtect, csrf
from config import Config
from redis import StrictRedis

import logging
from logging.handlers import RotatingFileHandler

logging.basicConfig(level=logging.DEBUG)
file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
formatter = logging.Formatter("%(levelname)s %(filename)s: %(lineno)d %(message)s")
file_log_handler.setFormatter(formatter)
logging.getLogger().addHandler(file_log_handler)

redis_store = StrictRedis(host=Config.REDIS_HOST, port=Config.REDIS_PORT, decode_responses=True)
db = SQLAlchemy()


# 用于存储验证码和短信验证码（移动至上方,程序才能运行）
# redis_store = StrictRedis(host=Config.REDIS_HOST, port=Config.REDIS_PORT)
# redis_store = StrictRedis(host="127.0.0.1", port=6379, decode_responses=True)

def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    db.init_app(app)
    Session(app)
    # csrf保护
    CSRFProtect(app)

    @app.after_request
    def after_request(response):
        csrf_token = csrf.generate_csrf()
        # print(csrf_token)
        response.set_cookie("csrf_token", csrf_token)
        return response

    # 导入自定义过滤器
    from info.utils.commons import rank_sort
    app.add_template_filter(rank_sort, "rank_sort")

    # 注意必须在该位置导入模块，否则会出现循环导入的错误
    from info.modules.news import news_blue
    app.register_blueprint(news_blue)
    from info.modules.passport import passport_blue
    app.register_blueprint(passport_blue)
    from info.modules.profile import profile_blu
    app.register_blueprint(profile_blu)
    from info.modules.admin import admin_blu
    app.register_blueprint(admin_blu)

    return app
